<template>
  <div>
    <h1>Vue MQTT Demo</h1>
    <div>
      <label for="topic">Topic:</label>
      <el-input type="text" v-model="topic" id="topic"/>
    </div>
    <div>
      <ul>
        <li>
          <p>{{log}}</p>
        </li>
      </ul>
    </div>
    <div>
      <label for="message">Message:</label>
      <el-input type="text" v-model="message" id="message"/>
    </div>
    <el-button @click="initMqtt">Mqtt Link</el-button>
    <el-button @click="mqttPublish">Send Message</el-button>
    <el-button @click="destroyed">Mqtt Close</el-button>
  </div>
</template>

<script>
  import mqtt from 'mqtt';

  export default {
    data() {
      return {
        client: '',
        topic: '',
        message: '',
        log:[],
      };
    },
    mounted() {
    },
    methods: {
      initMqtt() {
        let commonApi = "tcp://192.168.17.236:30745/mqtt";
        var options = {
          clientId: "123",
          protocolId: 'MQTT',
          protocolVersion: 4,
        };
        this.client = mqtt.connect(commonApi, options)
        this.client.on("connect", function () {
          console.log("连接成功")
        });
        this.client = mqtt.connect(commonApi, options)
        this.client.on("error", function () {
          console.log("error=>", err)
          this.client.end();
        });


      },
      mqttPublish() {
        let topic = "LMS/prod/toServer/oneBody/1/test001"
        this.client.publish(topic, JSON.stringify(this.message))
      },
      mqttReceive() {
        let topic = "LMS/prod/toTerminal/oneBody/1/test001"
        let vm = this;
        vm.client.subscribe(topic, function (err) {
          if (!err) {
            console.log("接收成功")
          } else {
            console.log("error=>", err)
          }
        });
        vm.client.on("message", function (topic, message) {
          vm.log.push(message);
          console.log("接受message:", message);
        })
      },
      destroyed() {
        this.client.on('end',function (err) {
          client.end()
          console.log("关闭成功")
        })
      },
    }
  };
</script>
